import { BusinessCode } from '../enums/business-code.enum';
import * as dayjs from 'dayjs';
import { HttpException } from "@nestjs/common";

export interface ApiResponseData<T> {
  code: number | string;
  message: string;
  result: T | null;
  success: boolean;
}

export class ApiResponse {
  // 需要格式化的字段名列表
  private static readonly formatFieldsArrData = ['updateTime', 'createTime'];
  private static formatDateFields(data: any): any {
    if (!data) return data;

    const queue = [data];
    while (queue.length > 0) {
      const current = queue.shift();
      if (Array.isArray(current)) {
        queue.push(...current);
      } else if (typeof current === 'object') {
        Object.entries(current).forEach(([key, value]) => {
          // 检查字段名是否在需要格式化的列表中
          if (this.formatFieldsArrData.includes(key)) {
            // 检查 value 是否为合法的日期类型
            if (
                typeof value === 'string' ||
                typeof value === 'number' ||
                value instanceof Date
            ) {
              if (dayjs(value).isValid()) {
                current[key] = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
              }
            }
          }

          // 递归处理嵌套对象/数组
          if (typeof value === 'object' || Array.isArray(value)) {
            queue.push(value);
          }
        });
      }
    }

    return data;
  }
  private static errorMapping = {
    [BusinessCode.BAD_REQUEST]: { status: 400, message: '请求错误' },
    [BusinessCode.INTERNAL_SERVER_ERROR]: { status: 500, message: '服务器错误' },
    [BusinessCode.NOT_FOUND]: { status: 404, message: '资源未找到，请核对资源路径！' },
  };

  static success<T extends Record<string, any>>(
    result: T | null,
    message?: string,
  ): ApiResponseData<T> {
    const newResult = this.formatDateFields(result)
    return {
      code: BusinessCode.SUCCESS,
      message: message || '成功啦',
      result: newResult,
      success: true,
    };
  }

  static fail<T>(code: BusinessCode, message?: string): HttpException {
    const { status, message: defaultMsg } = this.errorMapping[code] || {
      status: BusinessCode.INTERNAL_SERVER_ERROR,
      message: '未知错误',
    };
    const finalMessage = message || defaultMsg;
    throw new HttpException(
        {
          code: status,
          message: finalMessage,
          result: null,
          success: false,
        },
        status,
    );
  }
}
